package com.yuliang.ai.request;

import com.alibaba.fastjson.JSONObject;
import com.yuliang.ai.domain.Vo.ChatVo;
import com.yuliang.ai.domain.Vo.MessageVo;
import com.yuliang.utils.util.BeanUtils;
import com.yuliang.utils.util.CreateSign;
import com.yuliang.utils.util.HttpRequestUtils;
import com.yuliang.utils.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @author Huangkai
 */
@Slf4j
public class RequestUrlUtils {

    public static JSONObject request(ChatVo chatVo){
        String token = RedisUtils.get("token");
        log.info("token：{}", token);
        Map<String, String> header = new HashMap<>(2);
        Long time = System.currentTimeMillis() / 1000;
        Map<String, Object> params = new HashMap<>();
        params.put("stime", time);
        params.put("secret", "BearereyJhbGciOiJIUzUxMiJ9");
        String sortStr = CreateSign.getUrlParamsByMap(CreateSign.paramSort(params));
        String sign = DigestUtils.md5Hex(sortStr).toLowerCase();
        header.put("Content-Type", "application/json; charset=UTF-8");
        header.put("Authorization", token);
        header.put("Sign", sign);
        header.put("Stime", String.valueOf(time));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("project_id", chatVo.getProjectId());
        jsonObject.put("secret", chatVo.getSecret());
        jsonObject.put("title", chatVo.getTitle());
        jsonObject.put("chat_id", chatVo.getChatId());
        String responseContent = HttpRequestUtils.doPost("http://lsjllm.gsdata.cn:8066/api/chat/index/create", header, jsonObject.toJSONString());
        log.info("创建Ai会话返回的结果{}", responseContent);
        JSONObject resultObject = JSONObject.parseObject(responseContent);
        if(resultObject.getInteger("code") == 10000){
            JSONObject dataObject = resultObject.getJSONObject("data");
            log.info("设备id{}", chatVo.getDeviceId());
            MessageVo messageVo = new MessageVo();
            messageVo.setType("answer_chat");
            Integer chatAnsId = dataObject.getInteger("chatAnsId");
            Integer chatId = dataObject.getInteger("chatId");
            messageVo.setChatAnsId(chatAnsId);
            messageVo.setChatId(chatId);

            //五分钟的定时时间
            String connectionKey = chatVo.getDeviceId() + chatVo.getUserId()  + chatVo.getHumanIdentifyId();
            RedisUtils.setEx(connectionKey, JSONObject.toJSONString(messageVo), 5, TimeUnit.MINUTES);

            //保存设备信息，在websocket推送时，需要知道设备信息
            String key = "" + messageVo.getChatId() + messageVo.getChatAnsId();
            RedisUtils.setEx(key, JSONObject.toJSONString(chatVo), 10 , TimeUnit.MINUTES);
            //如果是空的，则重连
            if(SocketIOClientLaunch.socket == null || !SocketIOClientLaunch.socket.connected()){
                SocketIOClientLaunch.socket = null;
                log.info("大模型非连接中。。。");
                //重新连接
                SocketIOClientLaunch socketIOClientLaunch = BeanUtils.getBean("socketIOClientLaunch");
                socketIOClientLaunch.clientSocketIo();
            }
            log.info("是否连接{}", SocketIOClientLaunch.socket.connected());
            String messageJson = JSONObject.toJSONString(messageVo);
            log.info("传给大模型的参数{}", messageJson);
            SocketIOClientLaunch.socket.emit("socket_message", messageJson);
            return dataObject;
        }
        return null;
    }
}
